package service

import (
	"github.com/gin-gonic/gin"
	"mine-info-server/domain/plan-manage-context/model/plan-aggregate/aggregate"
	"mine-info-server/domain/plan-manage-context/model/plan-aggregate/entity"
	"mine-info-server/domain/plan-manage-context/repo"
)

/*
	领域服务可用于实体之间的组装。（涉及多个领域对象时使用）
*/

type PlanManageDomainService struct {
	PlanManageRepo repo.PlanManageIRepo
}

func NewPlanManageDomainService(planManageRepo repo.PlanManageIRepo) *PlanManageDomainService {
	return &PlanManageDomainService{PlanManageRepo: planManageRepo}
}

func (p *PlanManageDomainService) DeletePlan(ctx *gin.Context, plan *aggregate.PlanAggregate) error {
	// 删除里面所有待办以及待办项
	err := p.PlanManageRepo.DeleteTaskByPlanId(ctx, plan)
	if err != nil {
		return err
	}
	err = p.PlanManageRepo.DeleteTaskItemByPlanId(ctx, plan)
	if err != nil {
		return err
	}
	// 删除问题集内容/报告内容/计划明细/计划（这里考虑他们删除都是一起删，就没必要做拆分）
	err = p.PlanManageRepo.DeletePlan(ctx, plan)
	if err != nil {
		return err
	}
	// 发布计划删除的领域事件
	return nil
}

func (p *PlanManageDomainService) EditTaskItem(context *gin.Context, planId string, id string, level int, content string, executeDate string) error {
	var plan2 *aggregate.PlanAggregate
	// 查找对应的待办项
	plan, err := p.PlanManageRepo.GetTaskItemById(context, id)
	if err != nil {
		return err
	}
	// 判断是否更换计划
	if plan.PlanId != planId {
		plan2, err = p.PlanManageRepo.FindPlanContainsTaskByPlanIdAndDate(context, planId, executeDate)
		if err != nil {
			return err
		}
		// 判断是否有新待办需要添加
		if len(plan2.Tasks) != 0 {
			// 把A计划的待办项放到B计划中
			plan2.Tasks[0].TaskItems = append(plan2.Tasks[0].TaskItems, plan.Tasks[0].TaskItems...)
		} else {
			// 没有就新建一个
			task := entity.NewTask()
			task.Create(executeDate)
			plan2.Tasks = append(plan2.Tasks, task)
			plan2.Tasks[0].TaskItems = append(plan2.Tasks[0].TaskItems, plan.Tasks[0].TaskItems...)
		}
		// 持久化
		return p.PlanManageRepo.EditTaskItem(plan2)
	}
	// 判断是否更换待办时间
	if plan.Tasks[0].ExecuteDate != executeDate {
		// 先查询是否需要新待办
		task, err := p.PlanManageRepo.FindTaskByPlanIdAndDate(context, plan.PlanId, executeDate)
		if err != nil {
			return err
		}
		if task == nil {
			newTask := entity.NewTask()
			newTask.Create(executeDate)
			plan.ReplaceTask(newTask)
		} else {
			// 如果有就直接更换
			plan.ReplaceTask(task[0])
		}
	}
	// 判断是否更改了计划
	err = plan.EditTaskItem(level, content, executeDate)
	if err != nil {
		return err
	}
	return p.PlanManageRepo.EditTaskItem(plan)
}
